# -*- coding: utf-8 -*-
#
# File: ARFilePreview/views.py
#
# Copyright (c) 2007 atReal

#

"""
$Id$
"""

__author__ = """Jean-Nicolas Bès <contact@atreal.net>"""
__docformat__ = 'plaintext'
__licence__ = 'GPL'

# Imports: Zope
#from Acquisition import aq_inner
from Products.Five  import BrowserView
#from zope.event import notify
from zope.interface import implements

# Imports: CMF
#from Products.CMFCore.utils import getToolByName

# Import Plone
#from Products.CMFPlone import MessageFactory
#mf = MessageFactory('eventsubscription')

# Imports: ARDeadline
from Products.ARFilePreview.interfaces import IPreviewable,ICountable,ITrackDownload,ClickEvent
from Products.ARFilePreview.interfaces import IPreviewProvider,ICountProvider
from Products.Archetypes.BaseObject import Wrapper
from zope import event

from zope.component import getMultiAdapter
class TrackDownload(BrowserView):
    implements(ITrackDownload)
    def __init__(self,context,request):
        self.context = context
        self.request = request
        self.object = ITrackDownload(context)
    def getDldCount(self):
        return self.object.getDldCount()
    def setDldCount(self,num=1):
        self.object.setDldCount(num)
    def updateDldCount(self):
        self.object.updateDldCount()
    def download_url(self):
#        import pdb
#        pdb.set_trace()
        portal_state = getMultiAdapter((self.context, self.request), name=u'plone_portal_state')
        loginurl = portal_state.portal_url() + "/login_form"  
        if portal_state.anonymous():
            self.request.response.redirect(loginurl) 
        else:                                  
            self.updateDldCount()
            self.request.response.redirect(self.context.absolute_url())
class CountProvider(BrowserView):
    implements(ICountProvider)
    def __init__(self,context,request):
        self.context = context
        self.request = request
        self.object = ICountable(context)
    def getCount(self):
        event.notify(ClickEvent(self.object))
        self.updateCount()
        return self.object.getCount()
    def setCount(self,num):
        self.object.setCount(num)
        
    def updateCount(self):
        self.object.updateCount()
        

class PreviewProvider( BrowserView ):
    implements( IPreviewProvider )    
  
    def __init__(self, context, request):
        self.context = context
        self.request = request
        self.object = IPreviewable(context)
        
    def hasPreview(self):        
        return self.object.hasPreview()  

#    @memoize
    def parentobjurl(self):
        parent = self.context.aq_inner.aq_parent
        return parent.absolute_url()
    def getobjid(self):
        portal_state = getMultiAdapter((self.context, self.request), name=u'plone_context_state')            
        return portal_state.object_title()
        
    def external_edit_url(self):
        import string
        portal_state = getMultiAdapter((self.context, self.request), name=u'plone_context_state')
       
        objurl = portal_state.object_url()

#        objurl = string.replace(objurl,".org",".org:8280/oa")
        last = string.rfind(objurl,"/")
        return objurl[:last+1] + "externalEdit_/" + objurl[last+2:]
        
    
    def getPreview(self):        
        return self.object.getPreview()
    
    def updatePreview(self):        
        self.object.buildAndStorePreview()    

    ## XXX This should NOT be here !!
    ## but I wanted the feature badly...
    def updateAllPreviews(self):
        """
        """
        pc = self.context.portal_catalog
        brains = pc(portal_type='File')
        status=""
        for brain in brains:
            status+="<div>"+brain.getPath()
            try:
                obj=brain.getObject()
                IPreviewable(obj).buildAndStorePreview()
                obj.reindexObject()
            except Exception, e:
                status+=" %s %s</div>" % (str(e.__class__.__name__), str(e))
            else:
                status+=" OK</div>\n"
        return status


    def __bobo_traverse__(self, REQUEST, name):
        '''transparent access to document subobjects
        '''
        try:
            data, mime = self.object.getSubObject(name)
        except AttributeError:
            pass
        else:
            return Wrapper(data, name, mime).__of__(self)
        return getattr(self, name)

